import { Script } from "oasis-engine";
import { RoleScript } from "../role";
import { Table } from "../type";
import { TableManager } from "./objects/TableManager";

export class SceneScript extends Script {
  private roleScript: RoleScript;
  private tableList: Table[] = [];
  private _currentTable: Table;
  private _targetTable: Table;
  private tableManager: TableManager;

  get currentTable() {
    return this._currentTable;
  }

  get targetTable() {
    return this._targetTable;
  }

  onAwake() {
    const ground = this.entity.createChild("ground");
    this.tableManager = new TableManager(this.engine, ground);
    this.roleScript = this.entity.findByName("role").getComponent(RoleScript);
  }

  updateNextTable() {
    this._currentTable = this._targetTable;
    console.log(this._targetTable.entity.transform.position);
    this._targetTable = this.addNextTable();
  }

  private addNextTable() {
    const currentPosition = this._currentTable.entity.transform.position;
    if (Math.random() > 0.5) {
      const nextX = currentPosition.x + this.getRandomDistance();
      return this.tableManager.createCuboid(
        nextX,
        currentPosition.y,
        currentPosition.z
      );
    } else {
      const nextZ = currentPosition.z - this.getRandomDistance();
      return this.tableManager.createCuboid(
        currentPosition.x,
        currentPosition.y,
        nextZ
      );
    }
  }

  /** 台子距离 */
  private getRandomDistance() {
    return 20 + Math.floor(Math.random() * 40);
  }

  reset() {
    this.tableManager.clearAll();
    this.roleScript.reset();
    this._currentTable = this.tableManager.createCuboid(-15, 0, 0, false);
    const table = this.tableManager.createCuboid(25, 0, 0, false);
    this._targetTable = table;
    this.tableList = [this._currentTable, table];
  }
}
